import { useHistory } from "react-router-dom";
import { Redirect } from "react-router-dom";
import "../common/css/login.less";
import { useIntl, FormattedMessage } from "react-intl";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { Form, Input, Button } from "antd";
import { login } from "../api/api";
import { message } from "antd";

import { messages } from "../language/intl";

type IntlMessage = keyof typeof messages;

export default function Login() {
  const history = useHistory();
  const intl = useIntl();
  const getIntlMessage = (id: IntlMessage) => intl.formatMessage(messages[id]);
  const formTitle = getIntlMessage("formTitle");
  const loginBtn = getIntlMessage("loginBtn");

  const handleLogin = async (values: any) => {
    const res: any = await login(values);
    console.log(res.data);
    if (res.data.code === 10000) {
      localStorage.setItem("token", res.data.data.token);
      localStorage.setItem("menu", JSON.stringify(res.data.data.menu));
      history.push("/home");
    } else {
      message.error(res.data.message);
    }
  };

  return (
    <>
      <div className="login-wrapper">
        <Form
          name="login"
          className="login-form"
          initialValues={{
            remember: true,
          }}
          onFinish={handleLogin}
        >
          <FormattedMessage id="formTitle">
            {(text) => <h3 className="form-title">{text}</h3>}
          </FormattedMessage>
          <Form.Item
            name="username"
            rules={[{ required: true, message: getIntlMessage("usernameTip") }]}
          >
            <Input
              prefix={<UserOutlined size={24} />}
              placeholder={getIntlMessage("username")}
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: getIntlMessage("passwordTip") }]}
          >
            <Input.Password
              prefix={<LockOutlined size={24} />}
              placeholder={getIntlMessage("password")}
            />
          </Form.Item>
          <Form.Item>
            <FormattedMessage id="loginBtn">
              {(text) => (
                <Button
                  htmlType="submit"
                  className="login-form-button"
                  type="primary"
                >
                  {text}
                </Button>
              )}
            </FormattedMessage>
          </Form.Item>
          <Form.Item>
            <p className="tip">{`${getIntlMessage("username")}：admin ${getIntlMessage(
              "password"
            )}：${getIntlMessage("passwordContent")}  (${getIntlMessage("admin")})`}</p>
            <p className="tip">{`${getIntlMessage("username")}：editor ${getIntlMessage(
              "password"
            )}：${getIntlMessage("passwordContent")}  (${getIntlMessage("editor")})`}</p>
          </Form.Item>
        </Form>
      </div>
    </>
  );
}
